package com.alibaba.yygh.msm.controller;

import com.alibaba.yygh.common.result.R;
import com.alibaba.yygh.msm.service.MsmService;
import com.alibaba.yygh.msm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * description: MsmController
 * @author: gql
 * @date: 2021/11
 */
@RestController
@RequestMapping("/api/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 1.发送短信
     * @param phone 手机号
     * @return R
     */
    @GetMapping(value = "/send/{phone}")
    public R code(@PathVariable String phone) {
        // 如果在五分钟内发送过了验证码,不再继续发送
        String codeRedis = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(codeRedis)) {
            return R.ok();
        }
        // 1. 生成验证码-4位
        String code = RandomUtil.getFourBitRandom();
        // 2.调用第三方方法进行发送
        boolean isSuccess = false;

        try {
            isSuccess = msmService.sendShortMessage(phone, code);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (isSuccess) {
            /**
             * 发送成功,就把验证码放到redis中,设置有效时间
             * args1: key 手机号
             * args2: value 验证码
             * args3: 过期时间
             * args4: 过期时间单位
             */
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error();
        }
    }
}












